package middleware

import (
	"context"
	"eag_arch_layout/internal/model"
	utils2 "eag_arch_layout/internal/utils"
	"encoding/json"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
	"io"
)

// CreateQueryMapFromBody 从BODY获取查询MAP
func CreateQueryMapFromBody(logger log.Logger) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if tr, ok := transport.FromServerContext(ctx); ok {
				logger.Log(log.LevelInfo, "Operation", tr.Operation())
				utils := &utils2.SliceUtils[string]{
					TargetList: []string{"POST", "PUT", "DELETE"},
				}
				// 断言成HTTP的Transport可以拿到特殊信息
				if ht, ok := tr.(*http.Transport); ok && utils.Contains(ht.Request().Method) {
					bodyBytes, err := io.ReadAll(ht.Request().Body)
					if err != nil {
						logger.Log(log.LevelError, "异常", err)
					}
					defer ht.Request().Body.Close()
					var requestMap map[string]interface{}
					err = json.Unmarshal(bodyBytes, &requestMap)
					if err != nil {
						log.Error(err)
						logger.Log(log.LevelError, "异常", err)
					}
					ctx = context.WithValue(ctx, model.QUERY_MAP_KEY, requestMap)
				}

			}
			return handler(ctx, req)
		}
	}
}

func contrains(array []string, str string) bool {
	for _, v := range array {
		if v == str {
			return true
		}
	}
	return false
}
